package cn.iocoder.yudao.module.erp.service.contractinfo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.erp.dal.dataobject.planinfo.PlanInfoDO;
import cn.iocoder.yudao.module.erp.dal.mysql.planinfo.PlanInfoMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import cn.iocoder.yudao.module.erp.controller.admin.contractinfo.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.contractinfo.ContractInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.erp.dal.mysql.contractinfo.ContractInfoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

/**
 * 合同信息 Service 实现类
 *
 * @author mhc
 */
@Service
@Validated
public class ContractInfoServiceImpl implements ContractInfoService {

    @Resource
    private ContractInfoMapper contractInfoMapper;

    @Resource
    private PlanInfoMapper planInfoMapper;

    @Override
    public Long createContractInfo(ContractInfoSaveReqVO createReqVO) {
        // 插入
        ContractInfoDO contractInfo = BeanUtils.toBean(createReqVO, ContractInfoDO.class);

        contractInfo.setUsedCount(new BigDecimal("0"));
        contractInfo.setCompanyId(SecurityFrameworkUtils.getLoginUserDeptId());

        //计算每日用量
        BigDecimal all=contractInfo.getContractCount();
        //时间
        Date strat= DateUtil.date(createReqVO.getBeginTime());
        Date end=DateUtil.date(createReqVO.getEndTime());
        long dayDiff=DateUtil.between(strat,end, DateUnit.DAY)+1;
        BigDecimal avg=all.divide(new BigDecimal(dayDiff+""),4,
                RoundingMode.HALF_UP);
        //BigDecimal strippedNumber = avg.stripTrailingZeros();
        contractInfo.setContractDayCount(avg);

       // customerInfo.setCompanyId(SecurityFrameworkUtils.getLoginUserDeptId());
        contractInfoMapper.insert(contractInfo);
        // 返回
        return contractInfo.getId();
    }

    @Override
    public void updateContractInfo(ContractInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateContractInfoExists(updateReqVO.getId());
        // 更新
        ContractInfoDO updateObj = BeanUtils.toBean(updateReqVO, ContractInfoDO.class);

        //计算每日用量
        BigDecimal all=updateObj.getContractCount();
        //时间
        Date strat= DateUtil.date(updateObj.getBeginTime());
        Date end=DateUtil.date(updateObj.getEndTime());
        long dayDiff=DateUtil.between(strat,end, DateUnit.DAY)+1;
        BigDecimal avg=all.divide(new BigDecimal(dayDiff+""),4,
                RoundingMode.HALF_UP);
        //BigDecimal strippedNumber = avg.stripTrailingZeros();
        updateObj.setContractDayCount(avg);

        contractInfoMapper.updateById(updateObj);
    }

    @Override
    @Transactional
    public void deleteContractInfo(Long id) {
        // 校验存在
       // validateContractInfoExists(id);
        ContractInfoDO con=contractInfoMapper.selectById(id);
        if (con == null) {
            throw exception(CONTRACT_INFO_NOT_EXISTS);
        }
        // 删除
        //查询每日计划  采购
        if(con.getType().equals("1")){
            Long count=planInfoMapper.selectCount(new LambdaQueryWrapperX<PlanInfoDO>().eq(PlanInfoDO::getBuyContractId,id));
            if(count>0){
                throw exception(new ErrorCode(1_030_400_029, "存在关联此合同的每日计划，不可删除！"));
            }
        }else if(con.getType().equals("2")){
            Long count=planInfoMapper.selectCount(new LambdaQueryWrapperX<PlanInfoDO>().eq(PlanInfoDO::getSaleContractId,id));
            if(count>0){
                throw exception(new ErrorCode(1_030_400_029, "存在关联此合同的每日计划，不可删除！"));
            }
        }

        contractInfoMapper.deleteById(id);
    }

    private void validateContractInfoExists(Long id) {
        if (contractInfoMapper.selectById(id) == null) {
            throw exception(CONTRACT_INFO_NOT_EXISTS);
        }
    }

    @Override
    public ContractInfoDO getContractInfo(Long id) {
        return contractInfoMapper.selectById(id);
    }

    @Override
    public PageResult<ContractInfoDO> getContractInfoPage(ContractInfoPageReqVO pageReqVO) {
      /*  if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }*/

//        PageResult<ContractInfoDO> pageResult=contractInfoMapper.selectPage(pageReqVO);

         /* // 1.1 入库项
        List<ErpPurchaseInItemDO> purchaseInItemList = purchaseInService.getPurchaseInItemListByInIds(
                convertSet(pageResult.getList(), ErpPurchaseInDO::getId));
        Map<Long, List<ErpPurchaseInItemDO>> purchaseInItemMap = convertMultiMap(purchaseInItemList, ErpPurchaseInItemDO::getInId);
        // 1.2 产品信息
        Map<Long, ErpProductRespVO> productMap = productService.getProductVOMap(
                convertSet(purchaseInItemList, ErpPurchaseInItemDO::getProductId));
        // 1.3 供应商信息
        Map<Long, ErpSupplierDO> supplierMap = supplierService.getSupplierMap(
                convertSet(pageResult.getList(), ErpPurchaseInDO::getSupplierId));
        // 1.4 管理员信息
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(pageResult.getList(), purchaseIn -> Long.parseLong(purchaseIn.getCreator())));
        // 2. 开始拼接
        return BeanUtils.toBean(pageResult, ErpPurchaseInRespVO.class, purchaseIn -> {
            purchaseIn.setItems(BeanUtils.toBean(purchaseInItemMap.get(purchaseIn.getId()), ErpPurchaseInRespVO.Item.class,
                    item -> MapUtils.findAndThen(productMap, item.getProductId(), product -> item.setProductName(product.getName())
                            .setProductBarCode(product.getBarCode()).setProductUnitName(product.getUnitName()))));
            purchaseIn.setProductNames(CollUtil.join(purchaseIn.getItems(), "，", ErpPurchaseInRespVO.Item::getProductName));
            MapUtils.findAndThen(supplierMap, purchaseIn.getSupplierId(), supplier -> purchaseIn.setSupplierName(supplier.getName()));
            MapUtils.findAndThen(userMap, Long.parseLong(purchaseIn.getCreator()), user -> purchaseIn.setCreatorName(user.getNickname()));
        });*/

        return contractInfoMapper.selectPage(pageReqVO);
    }

}